<template>
  <div class="self_adaption">
    <div class="g-container">
      <div class="other">
        <p class="main_text">收车异常处理</p>
      </div>
      <!-- 搜索 -->
      <div class="g-search" ref="searchBox">
        <!-- 时间选择区域 -->
        <span class="demonstration">创建时间：</span>
        <el-date-picker
          v-model="searchValue.startAt"
          type="date"
          placeholder="开始时间"
          @change="startTime"
          :clearable="false"
          :default-time="defaultTime(0, 0, 0)" />
        <span class="demonstration" style="display: inline-block; font-size: 12px; color: #898989; margin: 20px"
          >至</span
        >
        <el-date-picker
          v-model="searchValue.endAt"
          type="date"
          placeholder="结束时间"
          @change="endTime"
          :clearable="false"
          :default-time="defaultTime1(23, 59, 59)" />
        <el-radio-group v-model="radio" class="ml-4" @change="radioSelect" style="margin-left: 10px">
          <el-radio label="1" size="large">今天</el-radio>
          <el-radio label="2" size="large">昨天</el-radio>
          <el-radio label="3" size="large">近3天</el-radio>
          <el-radio label="4" size="large">近1周</el-radio>
          <el-radio label="5" size="large">近1个月</el-radio>
          <el-radio label="6" size="large">近3个月</el-radio>
          <el-radio label="7" size="large">近1年</el-radio>
        </el-radio-group>
        <!-- 信息区域 -->
        <div class="all_select">
          <!-- 车牌号码 -->
          <div class="input_valye">
            <span class="demonstration">车牌号码：</span>
            <input
              type="text"
              class="input"
              placeholder="请输入车牌号码"
              style="width: 180px"
              v-model="searchValue.carNum"  @keyup.enter="search" />
          </div>
          <!-- 处理状态 -->
          <div class="input_valye">
            <span class="demonstration">处理状态：</span>
            <el-select v-model="searchValue.dealStatus" class="m-2" style="width: 180px" placeholder="请选择处理状态" @change="search">
              <el-option v-for="item in status_options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <!-- 底部按钮区域 -->
        <div class="bottom_btn">
          <el-button class="solid" @click="search">查询</el-button>
          <el-button class="hollow" @click="reset">重置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <!-- 顶部按钮区域 -->
        <div class="function_Btn" style="margin: 10px">
          <el-button class="hollow" @click="exportExcelList" v-if="roleList.write"> 导出订单信息 </el-button>
        </div>
        <!-- 表格区域 -->
        <el-table id="out-table" :data="tableData" style="width: 100%" :header-cell-style="{'text-align': 'center'}">
          <el-table-column prop="id" label="编号" align="center" />
          <el-table-column label="车牌号码" align="center" width="150">
            <template #default="item">
              {{ item.row.carInfo.号牌号码 }}
            </template>
          </el-table-column>
          <el-table-column prop="userPhone" label="联系方式" align="center" width="120" />
          <el-table-column prop="detailAddress" label="车辆所在地" align="center" width="250" />
          <el-table-column prop="description" label="异常情况" width="250" align="center" />
          <el-table-column prop="exceptionType" label="处理状态" align="center">
            <template #default="item">
              <span v-if="!item.row.exceptionType">未处理</span>
              <span v-else>已处理</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="处理说明" align="center" width="250" />
          <el-table-column prop="createdAt" label="创建时间" width="180" align="center" />
          <el-table-column prop="dealTime" label="处理时间" width="180" align="center" />
          <el-table-column label="操作" width="250" class="operation">
            <template #default="item">
              <div class="table_btn">
                <el-button size="small" class="none" @click="dispose(item.row)" v-if="!item.row.exceptionType"
                  >处理完成</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <smartPager
          v-model:current-page="searchValue.page"
          v-model:page-size="searchValue.rows"
          :total="total"
          @change="pageChange" />
      </div>
    </div>
    <!-- 站内信息 -->
    <div class="plateform" v-show="mask">
      <div class="title1">
        <div class="title_mes">
          <el-icon size="20" color="#fff"> <Edit /> </el-icon>&nbsp;处理说明
        </div>
        <span class="close" @click="maskBtn1">✖</span>
      </div>
      <div class="content1">
        <el-input
          v-model="dealDescription"
          cols="30"
          rows="4"
          class="form_input"
          type="textarea"
          maxlength="250"
          style="margin-top: 32px"
          placeholder="请输入处理说明"
          show-word-limit></el-input>
      </div>
      <div class="btn_center">
        <el-button class="hollow" @click="maskBtn1">取消</el-button>
        <el-button class="solid" @click="dealSure">确定</el-button>
      </div>
    </div>
    <!-- 遮罩层 -->
    <div id="mask1" v-if="mask" @click="maskBtn1"></div>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount} from 'vue';
import {RequestEstimateInfoList, RequestEstimateInfoDealInfo} from '@/api/path/index.js';
import {Edit} from '@element-plus/icons-vue';
import moment from 'moment';
import {ElMessage} from 'element-plus';
import useAuthorize from '@/hooks/authorize';
let roleList = useAuthorize();
const defaultTime = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};

const defaultTime1 = (H: any, M: any, S: any) => {
  var now = new Date();
  now.setHours(H);
  now.setMinutes(M);
  now.setSeconds(S);
  return now;
};
// 引入导出Excel表格依赖
import * as XLSX from 'xlsx';
/**
 * 导出信息
 */
const exportBox = ref([]);
const exportExcelList = async () => {
  exportBox.value = [];
  const a = await RequestEstimateInfoList({
    status: searchValue.value.status,
    dealStatus: searchValue.value.dealStatus,
    startAt: searchValue.value.startAt,
    endAt: searchValue.value.endAt,
    carNum: searchValue.value.carNum,
  });
  exportBox.value = a.resultObj.infos;
  const titleArr = [
    '编号',
    '车牌号码',
    '联系方式',
    '车辆所在地',
    '异常情况',
    '处理状态',
    '处理说明',
    '创建时间',
    '处理时间',
  ]; //表头中文名
  exportExcel(exportBox.value, titleArr, 'sheetName');
};
function exportExcel(json: any, titleArr: any, sheetName: any) {
  var data = new Array();
  var keyArray = new Array();
  const getLength = function (obj: any) {
    var count = 0;
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        count++;
      }
    }
    return count;
  };
  // 获取数组的length
  for (const key1 in json) {
    if (json.hasOwnProperty(key1)) {
      const element = json[key1];
      var rowDataArray = new Array();
      // 获取每一层里面有多少数据
      for (const key2 in element) {
        if (key2 == 'id') {
          if (element.hasOwnProperty(key2)) {
            rowDataArray[0] = element[key2];
            if (keyArray.length < getLength(element)) {
              keyArray.push(key2);
            }
          }
        } else if (key2 == 'carInfo') {
          if (element.hasOwnProperty(key2)) {
            rowDataArray[1] = JSON.parse(element[key2].value).号牌号码;
            if (keyArray.length < getLength(element)) {
              keyArray.push(key2);
            }
          }
        } else if (key2 == 'userPhone') {
          if (element.hasOwnProperty(key2)) {
            rowDataArray[2] = element[key2];
            if (keyArray.length < getLength(element)) {
              keyArray.push(key2);
            }
          }
        } else if (key2 == 'detailAddress') {
          if (element.hasOwnProperty(key2)) {
            rowDataArray[3] = element[key2];
            if (keyArray.length < getLength(element)) {
              keyArray.push(key2);
            }
          }
        } else if (key2 == 'description') {
          if (element.hasOwnProperty(key2)) {
            if (element[key2] != null) {
              rowDataArray[4] = element[key2];
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2);
              }
            }
          }
        } else if (key2 == 'exceptionType') {
          if (element.hasOwnProperty(key2)) {
            if (element[key2] != null) {
              rowDataArray[5] = element[key2] == 0 ? '未处理' : '已处理';
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2);
              }
            }
          }
        } else if (key2 == 'phone') {
          if (element.hasOwnProperty(key2)) {
            if (element[key2] != null) {
              rowDataArray[6] = element[key2];
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2);
              }
            }
          }
        } else if (key2 == 'createdAt') {
          if (element.hasOwnProperty(key2)) {
            if (element[key2] != null) {
              rowDataArray[7] = element[key2];
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2);
              }
            }
          }
        } else if (key2 == 'dealTime') {
          if (element.hasOwnProperty(key2)) {
            if (element[key2] != null) {
              rowDataArray[8] = element[key2];
              if (keyArray.length < getLength(element)) {
                keyArray.push(key2);
              }
            }
          }
        }
      }
      data.push(rowDataArray);
    }
  }
  // keyArray为英文字段表头
  data.splice(0, 0, keyArray, titleArr);
  console.log('data', data);
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  // 此处隐藏英文字段表头
  var wsrows = [{hidden: true}];
  ws['!rows'] = wsrows; // ws - worksheet
  XLSX.utils.book_append_sheet(wb, ws, sheetName);
  /* generate file and send to client */
  XLSX.writeFile(wb, '收车异常处理.xlsx');
}
const tableData = ref<any>([]); // 表格列表
const total = ref(0); //表格总数
const radio = ref('');
/**
 * 分页
 */
const pageChange = async (val: number) => {
  requestEstimateInfoList();
};
// 挂载
onMounted(() => {
  requestEstimateInfoList();
  handleResize();
  window.addEventListener('resize', handleResize);
});
const searchBox = ref();
const tablelistHeight = ref();
const handleResize = () => {
  const searchBoxHeight = searchBox.value.clientHeight;
  tablelistHeight.value = 110 + searchBoxHeight + 'px';
};

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
const requestEstimateInfoList = async () => {
  const a = await RequestEstimateInfoList(searchValue.value);
  tableData.value = a.resultObj.infos;
  tableData.value.forEach((item: any) => {
    item.carInfo = JSON.parse(item.carInfo.value);
  });
  total.value = a.resultObj.count;
  console.log('获取成功', tableData.value);
};
// 搜索参数
const searchValue = ref({
  carNum: '',
  status: '1',
  dealStatus: '',
  startAt: '',
  endAt: '',
  page: 1,
  rows: 10,
});
const status_options = ref([
  {
    label: '待处理',
    value: 0,
  },
  {
    label: '已处理',
    value: 1,
  },
]);
/**
 * 时间范围单选按钮
 */
const radioSelect = () => {
  searchValue.value.startAt = '';
  searchValue.value.endAt = '';
  var now = new Date();
  now.setHours(0);
  now.setMinutes(0);
  now.setSeconds(0);
  var now1 = new Date();
  now1.setHours(23);
  now1.setMinutes(59);
  now1.setSeconds(59);
  searchValue.value.endAt = moment(now1).format('YYYY-MM-DD HH:mm:ss');
  if (radio.value === '1') {
    searchValue.value.startAt = moment(now).format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '2') {
    searchValue.value.startAt = moment(now).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
    searchValue.value.endAt = moment(now1).subtract(1, 'days').format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '3') {
    searchValue.value.startAt = moment(now).subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '4') {
    searchValue.value.startAt = moment(now).subtract(1, 'weeks').format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '5') {
    searchValue.value.startAt = moment(now).subtract(1, 'months').format('YYYY-MM-DD HH:mm:ss');
  } else if (radio.value === '6') {
    searchValue.value.startAt = moment(now).subtract(3, 'months').format('YYYY-MM-DD HH:mm:ss');
  } else {
    searchValue.value.startAt = moment(now).subtract(1, 'years').format('YYYY-MM-DD HH:mm:ss');
  }
  search()
};
// 开始时间
const startTime = () => {
  searchValue.value.startAt.setHours(0);
  searchValue.value.startAt.setMinutes(0);
  searchValue.value.startAt.setSeconds(0);
  searchValue.value.startAt = moment(searchValue.value.startAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '0';
  search()
};
// 结束时间
const endTime = () => {
  searchValue.value.endAt.setHours(23);
  searchValue.value.endAt.setMinutes(59);
  searchValue.value.endAt.setSeconds(59);
  searchValue.value.endAt = moment(searchValue.value.endAt).format('yyyy-MM-DD HH:mm:ss');
  radio.value = '0';
  search()
};
/**
 * 搜索
 */
const search = async () => {
  // 判断开始时间不能早于当前时间
  if (moment(searchValue.value.startAt).diff(moment().format('YYYY-MM-DD HH:mm:ss')) >= 0) {
    ElMessage.error('开始时间不能晚于当前日期');
    searchValue.value.startAt = '';
  } else {
    // 判断是否两个时间都填写了
    if (searchValue.value.startAt !== '' && searchValue.value.endAt !== '') {
      // 判断开始时间不能晚于结束时间
      if (moment(searchValue.value.startAt).diff(moment(searchValue.value.endAt)) <= 0) {
        searchValue.value.page = 1;
        requestEstimateInfoList();
      } else {
        ElMessage.error('结束时间不能早于开始时间');
        searchValue.value.endAt = '';
      }
    } else {
      // 表示两个时间填写了任意一个
      searchValue.value.page = 1;
      requestEstimateInfoList();
    }
  }
};
/**
 * 点击重置
 */
const reset = () => {
  searchValue.value = {
    carNum: '',
    status: '1',
    dealStatus: '',
    startAt: '',
    endAt: '',
    page: 1,
    rows: 10,
  };
  requestEstimateInfoList();
  radio.value = '';
};
const dealDescription = ref('');
const infoId = ref();
const dispose = (item: any) => {
  mask.value = true;
  infoId.value = item.id;
};
const dealSure = async () => {
  const a = await RequestEstimateInfoDealInfo({
    infoId: infoId.value,
    dealDescription: dealDescription.value,
  });
  if (a.msg == '操作成功！') {
    ElMessage.success('处理成功！');
    searchValue.value.page = 1;
    requestEstimateInfoList();
  } else {
    ElMessage.error('处理失败，请重试！');
  }
  maskBtn1();
};
const mask = ref(false);
/**
 * 遮罩层数据
 */
const maskBtn1 = () => {
  mask.value = false;
  dealDescription.value = '';
};
</script>
<style lang="scss" scoped>
@import '@/assets/css/plateform/Article/Content.css';
@import '@/assets/css/plateform/Shop/GoodsManage.css';

.table {
  height: calc(100% - v-bind(tablelistHeight)) !important;
}

::v-deep .el-table--fit {
  height: calc(100% - 120px) !important;
}

.table :deep(.el-table__cell) {
  text-align: center;
}
.btn {
  width: 150px;
  position: absolute;
  right: 20px;
  bottom: 40px;
}

:deep(.el-input__wrapper) {
  width: 150px;
}
.plateform {
  width: 30%;
  height: 40%;
  position: absolute;
  background: #fff;
  z-index: 9999;
  top: 25%;
  left: 35%;

  .mes {
    margin-top: 20px;
    display: flex;
    align-items: center;

    .text {
      display: inline-block;
      width: 60px;
      font-size: 14px;
      color: #6c6c6c;
    }
  }
}
.el-table .warning-row {
  background: #44a2ff !important;
}

::deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  z-index: initial !important;
}

::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
  z-index: initial !important;
}
</style>
